/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.gui;

import br.com.controllers.Controller;
import br.com.models.Discipline;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.text.ParseException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Valdigleis
 */
public class SignDiscipline extends javax.swing.JDialog {

    
    private JFrame parent;
    
    private ArrayList<Discipline> disciplines;
    
    private MaskFormatter formatterName = new MaskFormatter();
    
    private MaskFormatter formatterCode = new MaskFormatter();
    
    private Discipline discipline = new Discipline();
    
    ArrayList<Discipline> pre;
    
    DefaultListModel model;
    
    /**
     * Creates new form SignDiscipline
     */
    public SignDiscipline(JFrame parent, ArrayList<Discipline> disciplines) {
        super(parent, true);
        initComponents();
        try{
            formatterName.setMask("U*************************************************");
            formatterName.setInvalidCharacters("0456789!?/|[]{}ªº°");
            formatterName.install(nameField);
            formatterCode.setMask("###UUU");
            formatterCode.setInvalidCharacters("!?/|[]{}ªº°");
            formatterCode.install(codeField);
        }catch(ParseException e){
            System.out.println(e.getMessage());
        }        
        this.parent = parent;
        this.disciplines = disciplines;
        this.parent = parent;
        this.discipline = new Discipline();
        this.pre = new ArrayList<Discipline>();
        this.model = new DefaultListModel();
        for(int i = 0; i < this.disciplines.size(); i++){
            this.model.addElement(this.disciplines.get(i).getName());
        }
        this.jList1.setModel(model);
        this.nameField.setText("");
        this.codeField.setText("");
        setResizable(false);
        Rectangle parentBounds = parent.getBounds();
        Dimension size = getSize();
        // Center in the parent
        int x = Math.max(0, parentBounds.x + (parentBounds.width - size.width) / 2);
        int y = Math.max(0, parentBounds.y + (parentBounds.height - size.height) / 2);
        setLocation(new Point(x, y));
        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nameField = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        codeField = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        semesterField = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        creditsField = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ficha");

        jLabel1.setText("Nome:");

        nameField.setToolTipText("Nome do componente.");
        nameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameFieldActionPerformed(evt);
            }
        });

        jLabel2.setText("Código:");

        codeField.setToolTipText("Código do componente.");

        jLabel3.setText("Semestre:");

        semesterField.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }));
        semesterField.setToolTipText("Selecione o semestre da disciplina");
        semesterField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                semesterFieldActionPerformed(evt);
            }
        });

        jLabel4.setText("Créditos");

        creditsField.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2", "4" }));
        creditsField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                creditsFieldActionPerformed(evt);
            }
        });

        jLabel5.setText("Pré-requisitos");

        jList1.setToolTipText("");
        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Gravar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Voltar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel6.setText("Segure a tecla \"ctrl\" para mulitplas seleções.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(semesterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(creditsField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(nameField))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(codeField)))
                .addGap(49, 49, 49))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(jLabel5))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel6)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(jButton1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jButton2)
                                        .addGap(41, 41, 41))
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))))))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(codeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(semesterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(creditsField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(45, 45, 45))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nameFieldActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.pre.clear();
        Controller controller = new Controller();
        getDiscipline();
        if(controller.checkCode(this.discipline.getCode())){
            JOptionPane.showMessageDialog(parent, "Esta código já está em uso por outra disciplina");
        }else{
            if(this.discipline.getPreRequisite().isEmpty() && !checkFields()){
                controller.saveDiscipline(discipline);
                JOptionPane.showMessageDialog(parent, "Disciplina gravada na base de dados!");
                this.dispose();
            }else{
                if(semesterField.getSelectedIndex()+1 > 1){
                    if(this.discipline.getPreRequisite().size() > 0){
                        if(checkPre(this.discipline.getPreRequisite())){
                            controller.saveDisciplineAndRequisitos(discipline);
                            JOptionPane.showMessageDialog(parent, "Disciplina gravada na base de dados!");
                            this.dispose();
                        }else{
                           JOptionPane.showMessageDialog(parent, "Pré-requisitos com semestre igual ou superior da Disciplina são inválidos!"); 
                        }
                        
                    }else{
                        controller.saveDiscipline(discipline);
                        JOptionPane.showMessageDialog(parent, "Disciplina gravada na base de dados!");
                        this.dispose();
                    }
                }else{
                    JOptionPane.showMessageDialog(parent, "Disciplinas de 1º periodo não tem pré-requisitos");
                }
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void creditsFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_creditsFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_creditsFieldActionPerformed

    private void semesterFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_semesterFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_semesterFieldActionPerformed

    private boolean checkFields(){
        return nameField.getText().trim().equals("") || codeField.getText().trim().equals("");
    }
    public void getDiscipline(){
        if(checkFields()){
            JOptionPane.showMessageDialog(parent, "O campo o nome e codigo é necessário por favor!");
        }else{
            this.discipline.setName(nameField.getText().trim());
            this.discipline.setCode(codeField.getText().trim());
            this.discipline.setSemester(semesterField.getSelectedIndex()+1);
            this.discipline.setCredits((creditsField.getSelectedIndex()+1)*2);
            if(jList1.isSelectionEmpty()){
               discipline.setPreRequisite(this.pre);
            }else{
                for(int i = 0; i < this.disciplines.size(); i++){
                   if(jList1.isSelectedIndex(i)){
                       this.pre.add(this.disciplines.get(i));
                   }
               }
               discipline.setPreRequisite(this.pre);
            }
            
        }
        
    }
    
    private boolean checkPre(ArrayList<Discipline> pre){
        for(int i = 0; i < pre.size(); i++){
            if(pre.get(i).getSemester() >= this.discipline.getSemester()){
                return false;
            }
        }
        return true;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField codeField;
    private javax.swing.JComboBox creditsField;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JFormattedTextField nameField;
    private javax.swing.JComboBox semesterField;
    // End of variables declaration//GEN-END:variables
}
